import random
import time

from libs import config
from libs.action import WebDriverAction
from libs.farm_helper import FarmHelper
from libs.game import Game
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.window import AdsWindow


def decide_farm_item():
    _, skills = game.get_skills()
    farm_level = skills.get('farm')
    if farm_level < 5:
        return 'popberry'
    if 5 <= farm_level < 15:
        return 'grainbow'
    if 15 <= farm_level < 25:
        return 'orange_grumpkin'
    if 25 <= farm_level < 30:
        return 'tato'
    if 30 <= farm_level < 35:
        return 'java'
    if 35 <= farm_level < 40:
        return 'muck'
    if 40 <= farm_level < 45:
        return 'napricot'
    if 45 <= farm_level < 75:
        return 'slothmato'
    if farm_level >= 75:
        return 'butterberry'

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Farm')
    parser.add_argument('--soil_id', type=int, help="土地ID")
    parser.add_argument('--farm_item', type=str, help="种植物品")

    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)
    user_id = args.user_id
    soil_id = args.soil_id

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver)
        movement = Movement(driver)
        log = Log(user_id)

        game.enter_game()
        action.escape()
        game.snapshot(user_id, 'farm_v2 start', include_skills=False)

        farm_item_key = decide_farm_item()
        farm_helper = FarmHelper(driver, user_id, farm_item_key, soil_id)

        prepare_fail = False
        total_round = 10
        for farm_round in range(total_round):
            if farm_helper.round_stop:
                break

            log.info(f"round {farm_round}/{total_round}, coin={game.get_coin()}")
            game.collect_mail()
            farm_item_key = decide_farm_item()
            log.info(f'farm {farm_item_key}')
            farm_helper.farm_item = config.get_farm_items().get(farm_item_key)
            try:
                if farm_helper.prepare_farm():
                    farm_helper.goto_farm_position()
                    farm_helper.farm()
                else:
                    if prepare_fail:
                        break
                    else:
                        prepare_fail = True
            except Exception as e:
                log.debug('exception occurred, refresh and retry')
                print(e)
                driver.refresh()
                time.sleep(5)
                game.enter_game()

    except Exception as e:
        raise e
